package com.example.user.myfirstapp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.example.user.myfirstapp.MainActivity;
import com.example.user.myfirstapp.MyApplication;
import com.example.user.myfirstapp.R;
import com.example.user.myfirstapp.common.Constant;
import com.example.user.myfirstapp.common.ImageHelper;
import com.example.user.myfirstapp.common.LoadingDialog;
import com.example.user.myfirstapp.entity.UserInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.makeramen.roundedimageview.RoundedImageView;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by user on 2016/9/21.
 */
public class UserCenterActivity extends Activity implements View.OnClickListener{
    private final int CAMERA_CODE = 10;
    private final int IMAGE_CODE = 11;
    public final int EDIT_IMAGE_CODE = 12;
    private Button bt_usercenter_return;
    private LinearLayout ll_userHead,ll_editPwd;
    private RoundedImageView iv_userHeadImg;
    private TextView tv_userName,tv_userType;
    private Button bt_loginOut;
    private Intent intent;
    private PopupWindow mPopWindow;
    private CheckBox cb_fingerprint;
    private int userId;
    private String Base64Str;
    private Boolean isEditHeadImg=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usercenter);

        tv_userName=(TextView)findViewById(R.id.tv_userName);
        tv_userType=(TextView)findViewById(R.id.tv_userType);
        iv_userHeadImg=(RoundedImageView)findViewById(R.id.iv_userHeadImg);

        //修改头像
        ll_userHead=(LinearLayout)findViewById(R.id.ll_userHead);
        ll_userHead.setOnClickListener(this);
        //返回按钮
        bt_usercenter_return=(Button)findViewById(R.id.bt_usercenter_return);
        bt_usercenter_return.setOnClickListener(this);
        //退出按钮
        bt_loginOut=(Button)findViewById(R.id.bt_loginOut);
        bt_loginOut.setOnClickListener(this);
        //修改密码
        ll_editPwd=(LinearLayout)findViewById(R.id.ll_editPwd);
        ll_editPwd.setOnClickListener(this);

        //从SharedPreferences中获取用户信息
        getUserInfo();

        //指纹
        cb_fingerprint=(CheckBox)findViewById(R.id.cb_fingerprint);
        cb_fingerprint.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    buttonView.setBackgroundResource(R.mipmap.checkbox_active);
                }
                else {
                    buttonView.setBackgroundResource(R.mipmap.checkbox);
                }
            }
        });
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_usercenter_return:
                //注：下面两种情况的页面切换都是从左进入，不同的是
                //startActivity(intent)，需用overridePendingTransition(R.animator.slide_left_in,0)
                //finish()，需用overridePendingTransition(0,R.animator.slide_right_out)
                // 具体原因有待研究，大概是：
                //public void overridePendingTransition (int enterAnim, int exitAnim)，enterAnim是Activity进入屏幕时的动画，exitAnim是Activity退出屏幕时的动画
                //startActivity是开始一个activity，所以第二个参数设置为0即可，
                //finish是关闭当前activity，所以第一个参数设置为0即可

                if(isEditHeadImg) {
                    //修改头像返回进入“我的”页面，重新加载用户头像
                    intent = new Intent(UserCenterActivity.this,MainActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putInt("openFragmentCode",4);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    //从左进入
                    this.overridePendingTransition(R.animator.slide_left_in,0);

                }
                //不修改头像
                else {
                    finish();
                    //从左往右切换(从左进入)
                    this.overridePendingTransition(0,R.animator.slide_right_out);
                }
                break;
            case R.id.bt_loginOut:
                //退出登录，跳到首页
                loginOut();
                break;
            case R.id.ll_editPwd:
                intent=new Intent(UserCenterActivity.this,EditPwdActivity.class);
                startActivity(intent);
                //从右往左切换
                this.overridePendingTransition(R.animator.slide_right_in,0);
                break;
            case R.id.ll_userHead:
                showPopupWindow();
                break;
            default:
                break;
        }
    }

    private void getUserInfo(){
        SharedPreferences sp = getSharedPreferences(Constant.sharedPreferences_user_key, Context.MODE_PRIVATE);
        String userJson = sp.getString("userJson", "");
        if (!TextUtils.isEmpty(userJson)) {
            Gson gson = new Gson();
            UserInfo user = gson.fromJson(userJson, new TypeToken<UserInfo>() {}.getType());
            if(!user.equals("null")){
                //用户id
                userId=user.getId();
                //用户名
                String name=user.getUserName();
                tv_userName.setText(name);
                //用户类型
                String type=user.getUserTypeName();
                tv_userType.setText(type);
                //读取头像(如果没有，就用默认头像)
                String imgUrl=user.getUserImg();
                if(!TextUtils.isEmpty(imgUrl)){
                    String url="http://"+ Constant.host+":"+Constant.port+"/"+imgUrl;
                    Glide.with(this).load(url).into(iv_userHeadImg);
                }
                else {
                    iv_userHeadImg.setImageResource(R.mipmap.head);
                }
            }
        }
    }

    //显示PopupWindow
    private void showPopupWindow(){
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popup_head_portrait, null);
        mPopWindow=new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setAnimationStyle(R.style.popupWindowAnim);
        mPopWindow.setOutsideTouchable(true);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_usercenter, null);
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);

        //点击PopWindow阴影事件
        RelativeLayout rl_popupbox=(RelativeLayout)contentView.findViewById(R.id.rl_popup_headPortrait);
        rl_popupbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePopup();
            }
        });

        //拦截点击事件，防止传到下一层rl_popupbox
        LinearLayout ll_popup_box=(LinearLayout)contentView.findViewById(R.id.ll_popup_box);
        ll_popup_box.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        //关闭按钮
        Button bt_popup_close=(Button)contentView.findViewById(R.id.bt_popup_close);
        bt_popup_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePopup();
            }
        });

        //我的相册
        Button bt_my_photo=(Button)contentView.findViewById(R.id.bt_my_photo);
        bt_my_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //先关闭Popup
                closePopup();
                getMyPhotos();
            }
        });

        //照相
        Button bt_take_photos=(Button)contentView.findViewById(R.id.bt_take_photos);
        bt_take_photos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private void closePopup(){
        mPopWindow.dismiss();
    }

    //获取相册
    private void getMyPhotos(){
        intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra("crop", "true");      //裁剪
        intent.putExtra("aspectX",1);         //X方向上的比例
        intent.putExtra("aspectY",1);         //y方向上的比例
        intent.putExtra("outputX", 80);       //裁剪区的宽
        intent.putExtra("outputY", 80);       //裁剪区的高
        intent.putExtra("return-data",true);  //是否将数据保留在Bitmap中返回
        // intent.putExtra("outputFormat", "JPEG");// 返回格式
        startActivityForResult(intent, IMAGE_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_CODE && resultCode == Activity.RESULT_OK) {

        }
        //相册
        else if (requestCode == IMAGE_CODE && resultCode == Activity.RESULT_OK) {
            Bundle bundle=data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");
            upLoadHeadImg(bitmap);
        }
    }

    private void upLoadHeadImg(Bitmap bitmap){
        //显示加载中
        LoadingDialog.showLoading(this, "请稍后...");
        final Bitmap bm=bitmap;
        //将bitmap转成Base64字符串
        Base64Str= ImageHelper.BitmapToStrByBase64(bitmap);
        //将Base64字符串上传至服务器
        String url = "http://" + Constant.host + ":" + Constant.port + "/api/UserInfo/EditHeadImg";
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (TextUtils.isEmpty(result) || result.equals("null")) {
                            Toast.makeText(getApplicationContext(), "修改头像失败",
                                    Toast.LENGTH_LONG).show();
                        }
                        else {
                            isEditHeadImg=true;
                            //显得到bitmap图片
                            iv_userHeadImg.setImageBitmap(bm);
                            //保存用户信息到SharedPreferences
                            saveUserToSharedPreferences(result);
                        }
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError err) {
                        Toast.makeText(getApplicationContext(), "网络请求失败",
                                Toast.LENGTH_LONG).show();
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("headImgStr", Base64Str);
                params.put("userId", Integer.toString(userId));
                return params;
            }
        };
        request.setTag("editheadImgRequest");
        MyApplication.getHttpQueue().add(request);
    }

    //修改SharedPreferences里的用户信息
    public void saveUserToSharedPreferences(String userInfoJson){
        //将用户信息保存在SharedPreferences里
        SharedPreferences sp = getSharedPreferences(Constant.sharedPreferences_user_key, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();//先清空
        editor.putString("userJson", userInfoJson);
        editor.commit();
    }

    //退出
    private void loginOut(){
        //获取自定义view
        View mDialogView = LayoutInflater.from(this).inflate(R.layout.dialog_login_out, null);
        mPopWindow = new PopupWindow(mDialogView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        mPopWindow.setOutsideTouchable(false);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_usercenter, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);

        //拦截点击事件，防止传到下一层
        RelativeLayout rl_dialog_login_out=(RelativeLayout)mDialogView.findViewById(R.id.rl_dialog_login_out);
        rl_dialog_login_out.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        //取消按钮
        Button bt_cancel=(Button)mDialogView.findViewById(R.id.bt_cancel);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });

        //确定退出
        Button bt_ok=(Button)mDialogView.findViewById(R.id.bt_ok);
        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //清空SharedPreferences
                SharedPreferences sp = getSharedPreferences(Constant.sharedPreferences_user_key, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.clear();
                editor.commit();

                //跳到首页
                intent=new Intent(UserCenterActivity.this, MainActivity.class);
                startActivity(intent);
                //从左进入
                overridePendingTransition(R.animator.slide_left_in,0);
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束时队列里面注销
        MyApplication.getHttpQueue().cancelAll("editheadImgRequest");
    }
}
